package com.hoshiicloud.user.service.impl.organization;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.aop.Logable;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.utils.UidGenerate4C;
import com.hoshiicloud.user.entity.company.Settlement;
import com.hoshiicloud.user.entity.organization.PlatOrganization;
import com.hoshiicloud.user.entity.platform.Platform;
import com.hoshiicloud.user.feign.IdGeneratorService;
import com.hoshiicloud.user.mapper.organization.PlatOrganizationMapper;
import com.hoshiicloud.user.service.company.ISettlementService;
import com.hoshiicloud.user.service.organization.PlatOrganizationService;
import com.hoshiicloud.user.service.platform.PlatformService;
import com.hoshiicloud.user.service.rbac.IMemberService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 机构表 服务实现类
 * </p>
 *
 * @author campchen
 * @since 2019-04-28
 */
@Service
public class PlatOrganizationServiceImpl extends ServiceImpl<PlatOrganizationMapper, PlatOrganization> implements PlatOrganizationService {

    @Autowired
    private IdGeneratorService idGeneratorService;
    @Autowired
    private PlatformService platformService;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private ISettlementService settlementService;

    /**
     * @return IPage
     * @description: 分页查询机构表
     */
    @Override
    @Logable(authName = "供应商信息-机构表管理-分页查询机构表")
    @Cacheable(cacheNames = "PlatOrganization", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    public IPage<PlatOrganization> getPage(IPage<PlatOrganization> page, QueryWrapper<PlatOrganization> queryWrapper, String key) {
        return baseMapper.selectPage(page, queryWrapper);
    }

    /**
     * @param id
     * @return com.hoshiicloud.organization.entity.PlatOrganization
     * @description: 根据id查询机构表
     */
    @Override
    @Cacheable(cacheNames = "PlatOrganization", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    @Logable(authName = "供应商信息-机构表 -查询机构表 ")
    public PlatOrganization getById(Long id) {
        return baseMapper.selectById(id);
    }

    /**
     * @Author:campchen
     * @Description:
     * @Date:下午 06:45 2019/5/11
     * @Param:
     * @return:
     */
    @Cacheable(cacheNames = "PlatOrganization", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#orgcode")
    @Logable(authName = "供应商信息-机构表 -查询机构表 ")
    @Override
    public PlatOrganization getByOrgcode(String orgcode) {
        Wrapper<PlatOrganization> wrapper = Wrappers.<PlatOrganization>query().lambda().eq(PlatOrganization::getOrgCode, orgcode);
        return baseMapper.selectOne(wrapper);
    }

    /**
     * @param entity
     * @return boolean
     * @description: 新增机构表
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "PlatOrganization", allEntries = true)
    @Logable(authName = "供应商信息-机构表-新增机构表")
    public String insert(PlatOrganization entity) {
        String id = idGeneratorService.queryGeneratorId();
        if (StringUtils.isBlank(id)) {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        Platform platform = platformService.getById(entity.getPlatId());
        if (null == platform) {
            throw new ServiceException("新增失败,平台信息有误");
        }
        Settlement settlement = settlementService.getById(entity.getPaymentId());
        if (null == settlement) {
            throw new ServiceException("新增失败,结算方式信息有误");
        }

        //判断编码是否可用
        String orgcode = null;
        Boolean flag = true;
        int num = 1;
        //生成7位编码
        UidGenerate4C idWorker = new UidGenerate4C(num);
        while (flag) {
            num++;
            orgcode = "5" + "2" + String.valueOf(idWorker.getNextId()).substring(10, 17);
            PlatOrganization comOrganizationOrgCode = getByOrgcode(orgcode);
            if (comOrganizationOrgCode == null || "".equals(comOrganizationOrgCode)) {
                flag = false;
            }
            //此处为强制结束条件，可根据实际得条件来进行判断。
            if (num > 1000) {
                throw new ServiceException(CommonError.error("新增失败,编码生成有误！"));
            }
        }
        entity.setOrgCode(orgcode);
        entity.setId(Long.parseLong(id));
        entity.setCreatedTime(LocalDateTime.now());
        int row = baseMapper.insert(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        return id;
    }

    /**
     * @param entity
     * @return boolean
     * @description: 修改机构表
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "PlatOrganization", allEntries = true)
    @Logable(authName = "供应商信息-机构表管理-修改机构表")
    public boolean updateById(PlatOrganization entity) {
        /**如果供应商资料已修改需重新审核供应商资料*/
        if (entity.getStatus() == null || "".equals(entity.getStatus())) {
            entity.setStatus(0);
        }
        entity.setModifiedTime(LocalDateTime.now());
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("修改失败"));
        }
        return true;
    }

    /**
     * @param id,status
     * @return boolean
     * @description: 修改机构表
     */
    @Override
    public boolean updateById(Long id, Integer status) {
        //审核状态只能为 0 1 2
        commonService.approval(status);
        PlatOrganization platOrganization = new PlatOrganization();
        platOrganization.setId(id);
        platOrganization.setStatus(status);
        platOrganization.setModifiedTime(LocalDateTime.now());
        int row = baseMapper.updateById(platOrganization);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("修改失败"));
        }
        return true;
    }

    /**
     * @param ids
     * @return com.hoshiicloud.organization.entity.PlatOrganization
     * @description: 根据id组查询机构表
     */
    @Override
    @Cacheable(cacheNames = "PlatOrganization", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    @Logable(authName = "供应商信息-机构表 -查询机构表 ")
    public List<PlatOrganization> getByIds(List<Long> ids, String key) {
        return baseMapper.selectBatchIds(ids);
    }

}
